const Dormitory = require('../models/dormitory');
const Student = require('../models/student');

// 宿舍控制器
const dormitoryController = {
  // 获取所有宿舍
  async getAllDormitories(ctx) {
    try {
      const dormitories = await Dormitory.find();
      ctx.body = {
        success: true,
        data: dormitories,
        count: dormitories.length
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '获取宿舍列表失败',
        error: error.message
      };
    }
  },

  // 根据ID获取宿舍
  async getDormitoryById(ctx) {
    try {
      const dormitory = await Dormitory.findById(ctx.params.id);
      if (!dormitory) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          message: '宿舍不存在'
        };
        return;
      }
      ctx.body = {
        success: true,
        data: dormitory
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '获取宿舍信息失败',
        error: error.message
      };
    }
  },

  // 创建宿舍
  async createDormitory(ctx) {
    try {
      const { building, roomNumber, type, capacity, floor, notes } = ctx.request.body;

      // 检查宿舍是否已存在
      const existingDorm = await Dormitory.findOne({ building, roomNumber });
      if (existingDorm) {
        ctx.status = 400;
        ctx.body = {
          success: false,
          message: '该宿舍已存在'
        };
        return;
      }

      // 创建宿舍
      const dormitory = new Dormitory({
        building,
        roomNumber,
        type,
        capacity,
        currentOccupancy: 0,
        floor,
        status: 'available',
        notes
      });
      await dormitory.save();

      ctx.status = 201;
      ctx.body = {
        success: true,
        message: '宿舍创建成功',
        data: dormitory
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '创建宿舍失败',
        error: error.message
      };
    }
  },

  // 更新宿舍信息
  async updateDormitory(ctx) {
    try {
      const dormitory = await Dormitory.findById(ctx.params.id);
      if (!dormitory) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          message: '宿舍不存在'
        };
        return;
      }

      const updateData = ctx.request.body;
      // 更新宿舍信息
      Object.assign(dormitory, updateData);
      await dormitory.save();

      ctx.body = {
        success: true,
        message: '宿舍信息更新成功',
        data: dormitory
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '更新宿舍信息失败',
        error: error.message
      };
    }
  },

  // 删除宿舍
  async deleteDormitory(ctx) {
    try {
      const dormitory = await Dormitory.findById(ctx.params.id);
      if (!dormitory) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          message: '宿舍不存在'
        };
        return;
      }

      // 检查宿舍是否有学生
      const studentCount = await Student.countDocuments({ dormitoryId: ctx.params.id });
      if (studentCount > 0) {
        ctx.status = 400;
        ctx.body = {
          success: false,
          message: '宿舍还有学生居住，无法删除'
        };
        return;
      }

      // 删除宿舍
      await Dormitory.findByIdAndDelete(ctx.params.id);

      ctx.body = {
        success: true,
        message: '宿舍删除成功'
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '删除宿舍失败',
        error: error.message
      };
    }
  },

  // 分页获取宿舍列表
  async getDormitoriesPaginated(ctx) {
    try {
      const page = parseInt(ctx.query.page) || 1;
      const limit = parseInt(ctx.query.limit) || 10;
      const skip = (page - 1) * limit;

      // 构建查询条件
      const query = {};
      if (ctx.query.building) {
        query.building = ctx.query.building;
      }
      if (ctx.query.type) {
        query.type = ctx.query.type;
      }
      if (ctx.query.status) {
        query.status = ctx.query.status;
      }

      const dormitories = await Dormitory.find(query)
        .skip(skip)
        .limit(limit)
        .sort({ building: 1, roomNumber: 1 });

      const total = await Dormitory.countDocuments(query);

      ctx.body = {
        success: true,
        data: dormitories,
        pagination: {
          total,
          page,
          limit,
          pages: Math.ceil(total / limit)
        }
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '获取分页宿舍列表失败',
        error: error.message
      };
    }
  },

  // 根据楼栋获取宿舍列表
  async getDormitoriesByBuilding(ctx) {
    try {
      const dormitories = await Dormitory.find({ building: ctx.params.building })
        .sort({ floor: 1, roomNumber: 1 });
      
      ctx.body = {
        success: true,
        data: dormitories,
        count: dormitories.length
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '获取楼栋宿舍列表失败',
        error: error.message
      };
    }
  },

  // 获取宿舍的学生列表
  async getDormitoryStudents(ctx) {
    try {
      const dormitory = await Dormitory.findById(ctx.params.id);
      if (!dormitory) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          message: '宿舍不存在'
        };
        return;
      }

      const students = await Student.find({ dormitoryId: ctx.params.id })
        .populate('classId userId');
      
      ctx.body = {
        success: true,
        data: students,
        count: students.length
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '获取宿舍学生列表失败',
        error: error.message
      };
    }
  },

  // 获取空宿舍列表
  async getEmptyDormitories(ctx) {
    try {
      const emptyDormitories = await Dormitory.find({ currentOccupancy: 0 })
        .sort({ building: 1, roomNumber: 1 });
      
      ctx.body = {
        success: true,
        data: emptyDormitories,
        count: emptyDormitories.length
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '获取空宿舍列表失败',
        error: error.message
      };
    }
  }
};

module.exports = dormitoryController;